// pages/index/index.js
const auth = require('../../api/auth');
const request = require('../../api/request');
const { processImageUrls } = require('../../utils/image');

Page({
  data: {
    userInfo: null,
    userPosition: '陈氏族人',
    todayReminders: [],
    familyStats: {
      totalMembers: 0,
      generations: 0,
      branches: 0,
      activeMembers: 0
    },
    familyNews: { list: [] },
    hotBranches: [],
    page: 1,
    size: 2,
    hasMore: true,
    loading: false
  },

  onLoad() {
    this.checkAuth();
  },

  onShow() {
    this.loadPageData();
    // 自动刷新动态列表
    this.loadFamilyNews(true);
  },

  // 检查登录状态
  checkAuth() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({ url: '/pages/login/index' });
      return;
    }
    this.loadUserInfo();
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo');
    console.log('loadUserInfo:', userInfo);
    if (userInfo) {
      this.setData({ userInfo });
    }
  },

  // 加载页面数据
  loadPageData() {
    this.loadTodayReminders();
    this.loadFamilyStats();
    this.loadFamilyNews();
    this.loadHotBranches();
  },

  // 加载今日提醒
  loadTodayReminders() {
    request.get('/home/reminders').then(res => {
      this.setData({ todayReminders: res.data });
    }).catch(err => {
      console.error('加载今日提醒失败:', err);
    });
  },

  // 加载家族统计
  loadFamilyStats() {
    const userInfo = this.data.userInfo || wx.getStorageSync('userInfo');
    const clanId = userInfo && userInfo.clanId;
    const url = clanId ? `/home/stats?clanId=${clanId}` : '/home/stats';
    request.get(url).then(res => {
      this.setData({ familyStats: res.data });
    }).catch(err => {
      console.error('加载家族统计失败:', err);
    });
  },

  // 加载家族动态
  loadFamilyNews(refresh = false) {
    if (this.data.loading) return;
    this.setData({ loading: true });
    const userInfo = this.data.userInfo || wx.getStorageSync('userInfo');
    const clanId = userInfo && userInfo.clanId;
    const page = refresh ? 1 : this.data.page;
    const size = this.data.size;
    const url = clanId ? `/home/news?clanId=${clanId}&page=${page}&size=${size}` : `/home/news?page=${page}&size=${size}`;
    const formatTime = (isoStr) => {
      if (!isoStr) return '';
      return isoStr.replace('T', ' ').split('.')[0];
    };
    request.get(url).then(res => {
        console.log(res)
      if (res.code == 0 && res.data) {
          
        res = res.data;
        console.log(res)
        res.list.forEach(item => {
          item.createTime = formatTime(item.createTime);
          item.isLiked = wx.getStorageSync(`liked_news_${item.id}`) === true;
          item.likeCount = item.like_count || 0;
          item.viewCount = item.view_count || 0;
        });
        res.list = processImageUrls(res.list, 'image');
        const newsIds = res.list.map(item => item.id);
        if (newsIds.length > 0) {
          request.get(`/home/news/likes?newsIds=${newsIds.join(',')}`)
            .then(likesData => {
              console.log(likesData)
              const token = wx.getStorageSync('token');
              if (token) {
                request.get(`/family-news/user-likes?newsIds=${newsIds.join(',')}`)
                  .then(userLikes => {
                    const likeMap = {};
                    if (userLikes && userLikes.length > 0) {
                      userLikes.forEach(like => {
                        likeMap[like.newsId] = true;
                      });
                    }
                    const newsList = res.list.map(item => {
                      item.isLiked = likeMap[item.id] || wx.getStorageSync(`liked_news_${item.id}`) === true;
                      const likeInfo = likesData.data.find(l => l.newsId === item.id);
                      if (likeInfo) {
                        item.likePeople = likeInfo.likeUsers ? likeInfo.likeUsers.split(',') : [];
                        item.likeCount = likeInfo.likeCount || item.likeCount || 0;
                      } else {
                        item.likePeople = [];
                        item.likeCount = item.likeCount || 0;
                      }
                      return item;
                    });
                    this.finishNewsLoading(refresh, newsList, res.list.length === size);
                  })
                  .catch(() => {
                    const newsList = res.list.map(item => {
                      const likeInfo = likesData.data.find(l => l.newsId === item.id);
                      if (likeInfo) {
                        item.likePeople = likeInfo.likeUsers ? likeInfo.likeUsers.split(',') : [];
                        item.likeCount = likeInfo.likeCount || item.likeCount || 0;
                      } else {
                        item.likePeople = [];
                        item.likeCount = item.likeCount || 0;
                      }
                      return item;
                    });
                    this.finishNewsLoading(refresh, newsList, res.list.length === size);
                  });
              } else {
                const newsList = res.list.map(item => {
                  const likeInfo = likesData.data.find(l => l.newsId === item.id);
                  if (likeInfo) {
                    item.likePeople = likeInfo.likeUsers ? likeInfo.likeUsers.split(',') : [];
                    item.likeCount = likeInfo.likeCount || item.likeCount || 0;
                  } else {
                    item.likePeople = [];
                    item.likeCount = item.likeCount || 0;
                  }
                  return item;
                });
                this.finishNewsLoading(refresh, newsList, res.list.length === size);
              }
            })
            .catch(() => {
              res.list.forEach(item => {
                item.likePeople = [];
              });
              this.finishNewsLoading(refresh, res.list, res.list.length === size);
            });
        } else {
          this.finishNewsLoading(refresh, res.list, res.list.length === size);
        }
      } else {
        this.finishNewsLoading(refresh, [], false);
      }
    }).catch(err => {
      this.setData({ loading: false });
      console.error('加载家族动态失败:', err);
    });
  },

  finishNewsLoading(refresh, list, hasMore) {
    this.setData({
      'familyNews.list': refresh ? list : this.data.familyNews.list.concat(list),
      page: refresh ? 2 : this.data.page + 1,
      hasMore,
      loading: false
    });
    wx.stopPullDownRefresh && wx.stopPullDownRefresh();
  },

  onPullDownRefresh() {
    this.loadFamilyNews(true);
  },

  onReachBottom() {
    // 移除家族动态的无限加载功能，保持固定显示2条
    // if (this.data.hasMore && !this.data.loading) {
    //   this.loadFamilyNews(false);
    // }
  },

  // 点赞或取消点赞
  toggleLike(e) {
    // 阻止事件冒泡，防止触发新闻详情页跳转
    e.stopPropagation && e.stopPropagation();
    
    const newsId = e.currentTarget.dataset.id;
    const news = this.data.familyNews.list;
    const index = news.findIndex(item => item.id === newsId);
    
    if (index === -1) return;
    
    const isLiked = !news[index].isLiked;
    const url = `/family-news/${newsId}/like`;
    const method = isLiked ? 'POST' : 'DELETE';
    
    request[method.toLowerCase()](url)
      .then(() => {
        // 更新点赞状态和计数
        news[index].isLiked = isLiked;
        news[index].likeCount = isLiked 
          ? (news[index].likeCount || 0) + 1 
          : Math.max(0, (news[index].likeCount || 0) - 1);
        
        // 保存点赞状态到本地存储
        wx.setStorageSync(`liked_news_${newsId}`, isLiked);
        
        this.setData({
          'familyNews.list': news
        });
      })
      .catch(err => {
        console.error('点赞操作失败:', err);
        wx.showToast({ 
          title: '操作失败，请重试', 
          icon: 'none' 
        });
      });
  },

  // 加载热门分支
  loadHotBranches() {
    const userInfo = this.data.userInfo || wx.getStorageSync('userInfo');
    const clanId = userInfo && userInfo.clanId;
    const url = clanId ? `/home/hot-branches?clanId=${clanId}` : '/home/hot-branches';
    
    request.get(url).then(res => {
      this.setData({ hotBranches: res.data });
    }).catch(err => {
      console.error('加载热门分支失败:', err);
    });
  },

  // 页面跳转方法
  goToMyFamily() {
    wx.navigateTo({ url: '/pages/familyintro/index' });
  },

  goToSearch() {
    wx.navigateTo({ url: '/pages/search/index' });
  },

  goToTree() {
    wx.switchTab({ url: '/pages/tree/index' });
  },

  goToTimeline() {
    wx.switchTab({ url: '/pages/timeline/index' });
  },

  goToSocial() {
    wx.switchTab({ url: '/pages/social/index' });
  },

  goToProfile() {
    wx.switchTab({ url: '/pages/profile/index' });
  },

  goToNews() {
    wx.navigateTo({ url: '/pages/familynews/list/index' });
  },

  goToBranch(e) {
    const branchId = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/branch/detail?id=${branchId}` });
  },

  viewNewsDetail(e) {
    const newsId = e.currentTarget.dataset.id;
    console.log('跳转详情页', e, newsId);
    wx.navigateTo({ url: `/pages/familynews/detail/index?id=${newsId}` });
  },

  // 扩展功能跳转
  goToAR() {
    wx.showToast({ title: 'AR功能开发中', icon: 'none' });
  },

  goToVoice() {
    wx.showToast({ title: '语音功能开发中', icon: 'none' });
  }
}); 